package com.siruier.boss.ui.activity.user

import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.isVisible
import com.siruier.boss.R
import com.siruier.boss.api.UserWithdrawal
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.loginApi
import com.siruier.boss.databinding.ActivityBaseRefreshBinding
import com.siruier.boss.databinding.ItemWithdrawalBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.base.BaseRecyclerAdapter
import com.siruier.boss.ui.dialog.showAlertDialog
import com.siruier.boss.ui.ext.drawable
import com.siruier.boss.ui.ext.toastMessageLong
import com.siruier.boss.ui.helper.RefreshHelper

class WithdrawalListActivity : BaseActivity<ActivityBaseRefreshBinding>() {

    private lateinit var mRefreshHelper: RefreshHelper<UserWithdrawal>
    private val mWithdrawalAdapter = WithdrawalAdapter()

    override fun initView() {
        vb.titleView.titleStr = "提现记录"
        mWithdrawalAdapter.setOnClickAdapterListenter(::onClick)
        mRefreshHelper = RefreshHelper(vb.refreshLayout, vb.recyclerView, mWithdrawalAdapter) { onReload() }
        mRefreshHelper.onRefresh()
    }

    private fun onReload() {
        launchUI({
            loginApi.withdrawRecord(mRefreshHelper.page).toData()?.records
        }, mRefreshHelper.handApiObserver())
    }

    private fun onClick(v: View, position: Int) {
        when (v.id) {
            R.id.buttonRevoke -> {
                showAlertDialog {
                    message(R.string.dialog_withdrawal_reback)
                    negativeButton { }
                    positiveButton {
                        (v.context as? BaseActivity<*>)?.launchUI({
                            loginApi.cancelWithdraw(mWithdrawalAdapter.getItem(position).id)
                        }, ApiObserver(v.context) {
                            "撤销成功".toastMessageLong()
                            onReload()
                        })
                    }
                }
            }
        }
    }

    class WithdrawalAdapter : BaseRecyclerAdapter<ItemWithdrawalBinding, UserWithdrawal>() {
        override fun onBindViewHolder(vb: ItemWithdrawalBinding, bean: UserWithdrawal, position: Int) {
            vb.run {
                bean.run {
                    tvRemark.text = "余额提现(${statusRemark})"
                    tvAmount.text = "$integral"
                    tvAddtime.text = addTime
                    buttonRevoke.isVisible = 0 == status
                    ViewCompat.setBackground(itemRoot, if (0 == status) R.drawable.bg_white_radius_6.drawable else R.drawable.bg_radius_6.drawable)
                    setViewClick(position, buttonRevoke)
                }
            }
        }
    }
}
